﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Twitterizer;

namespace MishraReader.Services
{
    internal class TwitterApi : ITwitterApi
    {
        public string CallbackUri { get; set; }
        public string ConsumerKey { get; set; }
        public string ConsumerKeySecret { get; set; }

        public Task<Uri> GetAuthorizationUriAsync(CancellationToken cancellationToken = default(CancellationToken))
        {
            // Twitterizer doesn't have an async api, so we're wrapping it all up in a
            // task for now
            var task = Task.Run(
                () =>
                    {
                        var response = OAuthUtility.GetRequestToken(ConsumerKey, ConsumerKeySecret, CallbackUri);

                        var authenticationUri = OAuthUtility.BuildAuthorizationUri(response.Token);

                        return authenticationUri;
                    }, cancellationToken);

            return task;
        }

        public bool IsSuccessful(Uri uri, out ITwitterAuthorization result)
        {
            result = null;

            if (uri.AbsoluteUri.Contains(CallbackUri))
            {
                var parameters = HttpUtility.ParseQueryString(uri.Query);

                result = new TwitterAuthorization(parameters);
                return true;
            }

            return false;
        }

        public Task<ITwitterToken> TranslateAuthorizationToTokenAsync(ITwitterAuthorization authorization,
                                                                      CancellationToken cancellationToken = default(CancellationToken))
        {
            // Twitterizer doesn't have an async api, so we're wrapping it all up in a
            // task for now
            var task = Task.Run(
                () =>
                    {
                        var requestToken = authorization.GetParameter("oauth_token");
                        var requestVerifier = authorization.GetParameter("oauth_verifier");

                        var token = OAuthUtility.GetAccessToken(ConsumerKey, ConsumerKeySecret, requestToken, requestVerifier);

                        ITwitterToken twitterToken = new TwitterToken(token.ScreenName, token.Token, token.TokenSecret);

                        return twitterToken;
                    }, cancellationToken);

            return task;
        }
    }

    internal class TwitterAuthorization : ITwitterAuthorization
    {
        private readonly NameValueCollection _nvc;

        public TwitterAuthorization(NameValueCollection nvc)
        {
            _nvc = nvc;
        }

        public bool IsAuthenticated
        {
            get
            {
                return !string.IsNullOrEmpty(_nvc["oauth_token"]) &&
                       !string.IsNullOrEmpty(_nvc["oauth_verifier"]);
            }
        }

        public string GetParameter(string value)
        {
            return _nvc[value];
        }
    }


    internal class TwitterToken : ITwitterToken
    {
        public TwitterToken(string screenName, string token, string tokenSecret)
        {
            ScreenName = screenName;
            Token = token;
            TokenSecret = tokenSecret;
        }

        public string ScreenName { get; private set; }
        public string Token { get; private set; }
        public string TokenSecret { get; private set; }
    }
}